module.exports = (options, app) => {
    return async function toHttps(ctx, next) {

        try {
            const configProxy = ctx.app.config.proxy;

            let clientIp = ctx.ip;
            // 判断是否开启了前置代理模式
            if (!configProxy) {
                if (ctx.header['X-Forwarded-For']) {
                    clientIp = ctx.header['X-Forwarded-For'].split(',')[0];
                } else if (ctx.header['x-real-ip']) {
                    clientIp = ctx.header['x-real-ip'];
                }
            };

            let isWhite = true,
                ipWhiteList = ctx.app.config.ipWhiteList;
            // 判断config中是否配置了白名单参数
            if (ctx.helper.isArray(ipWhiteList)) {
                if (ipWhiteList.length > 0) {
                    isWhite = ipWhiteList.some((item, index, array) => {
                        return item === clientIp;
                    });
                };
            }

            if (isWhite)
                await next();
            // else
            // ctx.body = 'illegal access';

        } catch (error) {
            ctx.logger.error(error);
        }

    };
};